﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.ComponentModel;
using Water.Web.Controls.BaseInterface;
using System.Web.UI.Design;
using System.Drawing.Design;
using System.Drawing;

[assembly: WebResource("Water.Resources.Default.JS.SuperButton.SuperButton.js", "text/javascript")]
namespace Water.Web.Controls
{
    [ToolboxData("<{0}:SuperButton runat=server></{0}:SuperButton>")/*, ParseChildren(true, "MenuItemList"), PersistChildren(false)*/]
    public class SuperButton : BaseWebControl, IPostBackEventHandler,IConfirm/*,IButtonControl*/
    {
        private static readonly object EventClick=new object();
        private static readonly object EventCommand=new object();
        private bool isClick;//是否有服务端事件
        private string js;
        private bool isDropDownLeftCap = false;
        private string popupControlId;
        private string reportId;

        public SuperButton() 
        {
        }

        #region properties
        
        ////MenuItemEditor
        //[Browsable(true), Category("Behavior"), GlobalizeDescription("MenuItemList"),
        //PersistenceMode(PersistenceMode.InnerDefaultProperty),
        //DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
        //Editor(typeof(Water.Web.Controls.Design.MenuItemEditor),typeof(UITypeEditor))]
        //public List<Water.Web.Controls.MenuItem> MenuItemList
        //{
        //    get { return menuItemList; }
        //    //set { menuItemList = value; }
        //}

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (string.IsNullOrEmpty(this.ToolTip))
                this.ToolTip = this.Text;
        }

        protected override HtmlTextWriterTag TagKey
        {
            get
            {
                return HtmlTextWriterTag.Table;
            }
        }

        [Browsable(true), Category("Behavior"), GlobalizeDescription("PopupControlId")]
        public string PopupControlId
        {
            get { return popupControlId; }
            set { popupControlId = value; }
        }

        [Browsable(true), Category("Behavior"), GlobalizeDescription("ReportId")]
        public string ReportId
        {
            get { return reportId; }
            set { reportId = value; }
        }

        [Browsable(true), Category("Behavior"), GlobalizeDescription("Text"),EditorBrowsable(EditorBrowsableState.Always)]
        public string Text
        {
            get
            {
                string str = (string)this.ViewState["Text"];
                if (str != null)
                {
                    return str;
                }
                else if (!string.IsNullOrEmpty(this.Prompt))
                {
                    if (DesignMode)
                        return this.Prompt;
                    else
                        return Water.Web.Prompt.PromptProxy.GetPromptDesc(this.Prompt);
                }
                else
                   return this.ID;
            }
            set
            {
                this.ViewState["Text"] = value;
            }

        }

        private string icon;

        [Browsable(true), GlobalizeDescription("Icon"), Category("Appearance"), Bindable(true), Editor("System.Web.UI.Design.ImageUrlEditor", typeof(UITypeEditor))]
        public string Icon
        {
            get 
            {
                if (string.IsNullOrEmpty(this.icon))
                {
                    string conmmandName = this.CommandName.ToLower();
                    switch (conmmandName)
                    {
                        case "edit":
                        case "update":
                        case "new":
                        case "insert":
                        case "cancel":
                        case "delete":
                        case "query":
                        case "select":
                        case "excel":
                            return Path.ResourcePath+"/Images/SuperButton/Icons/"+conmmandName + ".gif";
                            //break;
                    }
                }
                return icon;
            }
            set { icon = value; }
        }

        private bool onlyIcon = false;

        [Browsable(true), GlobalizeDescription("OnlyIcon"), Category("Appearance")]
        public bool OnlyIcon
        {
            get { return onlyIcon; }
            set { onlyIcon = value; }
        }


        private string onClientClick;

        [Browsable(true), Category("Behavior"), GlobalizeDescription("OnClientClick")]
        public virtual string OnClientClick
        {
            get
            {
                string str = this.onClientClick;
                if (str == null)
                {
                    if (CommandName.ToUpper() == "EXCEL" && !string.IsNullOrEmpty(ReportId))
                        return "excelReport('"+ReportId+"')";
                    return string.Empty;
                }
                return str;
            }
            set
            {
                this.onClientClick = value;
            }
        }


        private ButtonMode buttonDefaultMode = ButtonMode.Text;


        [Browsable(true), Category("Appearance"), GlobalizeDescription("ButtonDefaultMode"), DefaultValue(ButtonMode.Text)]
        public ButtonMode ButtonDefaultMode
        {
            get { return buttonDefaultMode; }
            set { buttonDefaultMode = value; }
        }


        private bool IsDropDownLeftCap
        {
            get
            {
                if (!string.IsNullOrEmpty(this.popupControlId) && (!string.IsNullOrEmpty(this.OnClientClick) || this.isClick || IsConfirm))
                    this.isDropDownLeftCap = true;
                return this.isDropDownLeftCap;
            }
        }

        private string PopupJS
        {
            get
            {
                if (string.IsNullOrEmpty(this.js))
                    this.js = this.CreateJS();
                return js;
            }
        }

        private string dialogId;

        [Browsable(true), GlobalizeDescription("DialogId"), Category("Behavior")]
        public string DialogId
        {
            get { return dialogId; }
            set { dialogId = value; }
        }
        

        #region IConfirm 成员
        private bool isConfirm;
        private string confirmText;

        [Browsable(true), Category("Behavior"), GlobalizeDescription("IsConfirm")]
        public bool IsConfirm
        {
            get
            {
                return this.isConfirm;
            }
            set
            {
                this.isConfirm = value;
            }
        }
        [Browsable(true), Category("Behavior"), GlobalizeDescription("ConfirmText")]
        public string ConfirmText
        {
            get
            {
                return this.confirmText;
            }
            set
            {
                this.confirmText = value;
            }
        }

   
        #endregion

        #endregion

        protected virtual void OnClick(EventArgs e)
        {
            EventHandler handler = (EventHandler)base.Events[EventClick];
            if (handler != null)
            {
                handler(this, e);
            }
        }

        protected virtual void OnCommand(CommandEventArgs e)
        {
            CommandEventHandler handler = (CommandEventHandler)base.Events[EventCommand];
            if (handler != null)
            {
                handler(this, e);
            }
            base.RaiseBubbleEvent(this, e);
        }


        #region IPostBackEventHandler 成员

        public void RaisePostBackEvent(string eventArgument)
        {
            
            //base.ValidateEvent(this.UniqueID, eventArgument);
            if (this.CausesValidation)
            {
                this.Page.Validate(this.ValidationGroup);
            }
            this.OnClick(EventArgs.Empty);
            this.OnCommand(new CommandEventArgs(this.CommandName, this.CommandArgument));

        }

        #endregion

        protected override void OnLoad(EventArgs e)
        {
            if (!this.Enabled)
            {
                string enable = @"$j('#__" + this.ClientID + "__').block({message:null,fadeIn:0,overlayCSS: { backgroundColor: '#fff',cursor:'default'}});";
                enable = @"$j(function() {" + enable + "});";
                this.UpdateJS = enable;
            }
            if (!string.IsNullOrEmpty(this.DialogId) && string.IsNullOrEmpty(this.OnClientClick))
            {
                string js = @"$j('#" + Util.Utils.FindControlEx(this.DialogId, this.Page).ClientID + "').showDialog('" + this.ClientID + ",1');return false";
                this.OnClientClick = js;
            }
            base.OnLoad(e);
            this.Page.ClientScript.RegisterClientScriptResource(typeof(SuperButton), "Water.Resources.Default.JS.SuperButton.SuperButton.js");
            PageManager.RegisterPageStyleSheet(this, "SuperButton_css", "CSS/SuperButton.css");
            
        }

        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);

            if (!this.Enabled)
            {
                string enable = @"$j('#__" + this.ClientID + "__').block({message:null,fadeIn:0,overlayCSS: { backgroundColor: '#fff',cursor:'default'}});";
                enable = @"$j(function() {" + enable + "});";
                this.Page.ClientScript.RegisterStartupScript(typeof(SuperButton), this.UniqueID, enable + "\n", true);
            }
        }

        private string CreateJS()
        {
            string js = "";
            if (!string.IsNullOrEmpty(this.PopupControlId))
            {
                Control ctl = this.FindControl(this.PopupControlId);
                if (this.IsDropDownLeftCap)
                {
                    if (null != ctl)
                    {
                        if (ctl is Water.Web.Controls.BaseInterface.IUpdatedableControl)
                        {
                            js = @"$j('#" + this.ClientID + "_dropdown').dropDownPopupControl('" + ctl.ClientID + "',true,'" + this.ClientID + "',event);";
                        }
                        else
                        {
                            js = @"$j('#" + this.ClientID + "_dropdown').dropDownPopupControl('" + ctl.ClientID + "',false,'" + this.ClientID + "',event);";
                        }
                    }
                    else
                    {
                        js = @"$j('#" + this.ClientID + "_dropdown').dropDownPopupControl('" + this.PopupControlId + "',false,'" + this.ClientID + "',event);";
                    }
                }
                else
                {
                    if (null != ctl)
                    {
                        if (ctl is Water.Web.Controls.BaseInterface.IUpdatedableControl)
                        {
                            js = @"$j('#" + this.ClientID + "').superButtonPopupControl('" + ctl.ClientID + "',true,event);";
                        }
                        else
                        {
                            js = @"$j('#" + this.ClientID + "').superButtonPopupControl('" + ctl.ClientID + "',false,event);";
                        }
                    }
                    else
                    {
                        js = @"$j('#" + this.ClientID + "').superButtonPopupControl('" + this.PopupControlId + "',false,event);";
                    }
                }
            }
            return js;
        }
       
        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            base.AddAttributesToRender(writer);
            if (ButtonDefaultMode == ButtonMode.Button)
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "superButton buttonTable");
            else
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "superTextButton buttonTable");
            writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "0");
            writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
            writer.AddAttribute(HtmlTextWriterAttribute.Title, this.ToolTip);
            writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID);
            if(this.IsDropDownLeftCap)
                writer.AddAttribute(HtmlTextWriterAttribute.Axis, "1");
            else
                writer.AddAttribute(HtmlTextWriterAttribute.Axis, "0");

            if(!string.IsNullOrEmpty(this.PopupControlId) && !this.IsDropDownLeftCap)
                writer.AddAttribute(HtmlTextWriterAttribute.Onclick,this.PopupJS);

            string js_confirm = string.Empty ;
            string js = string.Empty;
            if (this.isConfirm)
            {
                if (string.IsNullOrEmpty(this.ConfirmText))
                {
                    js_confirm = "window.confirm(\'" + Water.Resources.Globalize.DescriptionResource.DefaultConfirmText + "\')";
                }
                else
                {
                    js_confirm = "window.confirm(\'" + this.ConfirmText + "\')";
                }
            }
            if (string.IsNullOrEmpty(js_confirm))
            {
                js = Water.Util.Util.EnsureEndWithSemiColon(this.OnClientClick);
                //if (isClick)
                    js += Water.Util.Util.EnsureEndWithSemiColon(this.Page.ClientScript.GetPostBackEventReference(this, ""));
            }
            else
            {
                js = "if(" + js_confirm + ") {" + Water.Util.Util.EnsureEndWithSemiColon(this.OnClientClick);
                //if (isClick)
                   js += Water.Util.Util.EnsureEndWithSemiColon(this.Page.ClientScript.GetPostBackEventReference(this, ""));
                js += "}";
            }

            writer.AddAttribute(HtmlTextWriterAttribute.Onclick, js);
            if (this.DesignMode)
                writer.AddStyleAttribute(HtmlTextWriterStyle.BackgroundColor,"#f0f0f0");
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            RenderButton(writer);
            base.RenderContents(writer);
        }

        public override void RenderEndTag(HtmlTextWriter writer)
        {
            base.RenderEndTag(writer);
            //RenderPopupControl(writer);
        }

        private void RenderButton(HtmlTextWriter writer)
        {
            writer.RenderBeginTag(HtmlTextWriterTag.Tbody);//tbody begin
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);//tr begin

            RenderButtonLeftCap(writer);
            if (!string.IsNullOrEmpty(this.Icon))
                RenderButtonIcon(writer);
            if(!this.OnlyIcon)
               RenderButtonText(writer);

             if(this.IsDropDownLeftCap)
                RenderDropDownLeftCap(writer);

            if (!string.IsNullOrEmpty(this.popupControlId))
              RenderDropDownIconCell(writer);

            RenderButtonRightCap(writer);
            

            writer.RenderEndTag();//tr end
            writer.RenderEndTag();//tbody end
        }

        private  void RenderButtonLeftCap(HtmlTextWriter write)
        {
            //***** leftCap begin
            string _style = "leftCap";
            if (ButtonDefaultMode == ButtonMode.Button)
                _style += " " + _style + "over";
            write.AddAttribute(HtmlTextWriterAttribute.Class, _style);
            write.AddAttribute(HtmlTextWriterAttribute.Width, "3px");
 
            write.RenderBeginTag(HtmlTextWriterTag.Td);//td begin

            write.AddStyleAttribute(HtmlTextWriterStyle.Visibility, "hidden");
            write.AddStyleAttribute(HtmlTextWriterStyle.Width, "3px");
            write.RenderBeginTag(HtmlTextWriterTag.Div);//div begin
            write.RenderEndTag();//div end

            write.RenderEndTag();//td end
            //***** leftCap end
        }

        private  void RenderButtonRightCap(HtmlTextWriter write)
        {
            //***** rightCap begin
            string _style = "rightCap";
            if (ButtonDefaultMode == ButtonMode.Button)
                _style += " " + _style + "over";
            write.AddAttribute(HtmlTextWriterAttribute.Class, _style);
            write.AddAttribute(HtmlTextWriterAttribute.Width, "3px");
            if (this.IsDropDownLeftCap)
            {
                write.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID + "_rightCap");
                write.AddAttribute(HtmlTextWriterAttribute.Onclick, this.PopupJS);
            }
            write.RenderBeginTag(HtmlTextWriterTag.Td);//td begin

            write.AddStyleAttribute(HtmlTextWriterStyle.Visibility, "hidden");
            write.AddStyleAttribute(HtmlTextWriterStyle.Width, "3px");
            write.RenderBeginTag(HtmlTextWriterTag.Div);//div begin
            write.RenderEndTag();//div end

            write.RenderEndTag();//td end
            //***** rightCap end
        }

        private void RenderButtonText(HtmlTextWriter write)
        {
            string _style = "labelCell";
            if (ButtonDefaultMode == ButtonMode.Button)
                _style += " " + _style + "over";
            write.AddAttribute(HtmlTextWriterAttribute.Class, _style);
   
            write.RenderBeginTag(HtmlTextWriterTag.Td);//td begin
            write.Write(this.Text);
            write.RenderEndTag();//td end
        }

        private void RenderButtonIcon(HtmlTextWriter write)
        {
            //***** rightCap begin
            string _style = "buttonIconCell";
            if (ButtonDefaultMode == ButtonMode.Button)
                _style += " " + _style + "over";
            write.AddAttribute(HtmlTextWriterAttribute.Class, _style);

            write.RenderBeginTag(HtmlTextWriterTag.Td);//td begin


            if (!string.IsNullOrEmpty(this.Icon))
            {
                write.AddAttribute(HtmlTextWriterAttribute.Src, this.ResolveClientUrl(this.Icon));
                write.AddAttribute(HtmlTextWriterAttribute.Border, "0");
                write.RenderBeginTag(HtmlTextWriterTag.Img);//img begin
                write.RenderEndTag();//img end
            }

            write.RenderEndTag();//td end
        }

        private void RenderDropDownIconCell(HtmlTextWriter write)
        {
            string _style = "dropDownIconCell";
            if (ButtonDefaultMode == ButtonMode.Button)
                _style += " " + _style + "over";
            write.AddAttribute(HtmlTextWriterAttribute.Class, _style);
            if (this.IsDropDownLeftCap)
            {
                write.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID + "_dropDownIconCell");
                write.AddAttribute(HtmlTextWriterAttribute.Onclick, this.PopupJS);
            }

            write.RenderBeginTag(HtmlTextWriterTag.Td);//td begin

            string _styleComboArrow = "comboArrow";
            if (ButtonDefaultMode == ButtonMode.Button)
                _styleComboArrow += " " + _styleComboArrow + "over";

            if (this.IsDropDownLeftCap)
            {
                write.AddAttribute(HtmlTextWriterAttribute.Class, _styleComboArrow + " isDropDownLeftCap");
            }
            else
                write.AddAttribute(HtmlTextWriterAttribute.Class, _styleComboArrow);
            write.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID+"_dropdown");
            write.RenderBeginTag(HtmlTextWriterTag.Div);//div begin
            write.RenderEndTag();//div end

            write.RenderEndTag();//td end
        }

        private void RenderDropDownLeftCap(HtmlTextWriter write)
        {
            string _style = "dropDownLeftCap";
            if (ButtonDefaultMode == ButtonMode.Button)
                _style += " " + _style + "over";
            write.AddAttribute(HtmlTextWriterAttribute.Class, _style);
            write.RenderBeginTag(HtmlTextWriterTag.Td);//td begin

            write.AddStyleAttribute(HtmlTextWriterStyle.Visibility, "hidden");
            write.AddStyleAttribute(HtmlTextWriterStyle.Width, "2px");
            write.RenderBeginTag(HtmlTextWriterTag.Div);//div begin
            write.RenderEndTag();//div end

            write.RenderEndTag();//td end
        }
             
        #region IButtonControl 成员
        [Category("Action"), GlobalizeDescription("Click")] 
        public event EventHandler Click
        {
            add
            {
                Events.AddHandler(EventClick, value);
                isClick = true;
            }
            remove
            {
                Events.RemoveHandler(EventClick, value);
                isClick = false;
            }
        }
       
        [Category("Action"), GlobalizeDescription("Command")]
        public event CommandEventHandler Command
        {
            add
            {
                Events.AddHandler(EventCommand, value);
            }
            remove
            {
                Events.RemoveHandler(EventCommand, value);
            }
        }


        [DefaultValue(true), GlobalizeDescription("CausesValidation"), Themeable(false), Category("Behavior")]
        public bool CausesValidation
        {
            get
            {
                object obj2 = this.ViewState["CausesValidation"];
                if (obj2 != null)
                {
                    return (bool)obj2;
                }
                return true;
            }
            set
            {
                this.ViewState["CausesValidation"] = value;
            }

        }

        [DefaultValue(""), Themeable(false), Category("Behavior"), GlobalizeDescription("CommandArgument"), Bindable(true)]
        public string CommandArgument
        {
            get
            {
                string str = (string)this.ViewState["CommandArgument"];
                if (str != null)
                {
                    return str;
                }
                return string.Empty;
            }
            set
            {
                this.ViewState["CommandArgument"] = value;
            }

        }
        [DefaultValue(""), Themeable(false), Category("Behavior"), GlobalizeDescription("CommandName"), Bindable(true)]
        public string CommandName
        {
            get
            {
                string str = (string)this.ViewState["CommandName"];
                if (str != null)
                {
                    return str;
                }
                return string.Empty;
            }
            set
            {
                this.ViewState["CommandName"] = value;
                if (value.ToLower() == "delete")
                    this.IsConfirm = true;
            }

        }

        [DefaultValue(""), UrlProperty("*.aspx"), GlobalizeDescription("PostBackUrl"), Editor("System.Web.UI.Design.UrlEditor", typeof(UITypeEditor)), Themeable(false), Category("Behavior")]
        public string PostBackUrl
        {
            get
            {
                string str = (string)this.ViewState["PostBackUrl"];
                if (str != null)
                {
                    return str;
                }
                return string.Empty;
            }
            set
            {
                this.ViewState["PostBackUrl"] = value;
            }

        }

        [DefaultValue(""), GlobalizeDescription("ValidationGroup"), Category("Behavior"), Themeable(false)]
        public virtual string ValidationGroup
        {
            get
            {
                string str = (string)this.ViewState["ValidationGroup"];
                if (str != null)
                {
                    return str;
                }
                return string.Empty;
            }
            set
            {
                this.ViewState["ValidationGroup"] = value;
            }
        }


        #endregion
    }

    public enum ButtonMode
    {
        Button,
        Text
    }
}
